package com.rpc.example.protocol;

import com.rpc.example.handler.RpcServerInitHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {

    private String inetAddress;

    private Integer inetPort;

    public NettyServer(String inetAddress, Integer inetPort) {
        this.inetAddress = inetAddress;
        this.inetPort = inetPort;
    }

    public void startServer() {
        log.info("++++++++start netty server++++++++++");
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup workers = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, workers)
                .channel(NioServerSocketChannel.class)
                .childHandler(new RpcServerInitHandler())
        ;
        try {
            ChannelFuture future = bootstrap.bind(this.inetAddress, this.inetPort).sync();
            log.info("++++++++start netty server success on :{} {} ++++++++++", inetAddress, inetPort);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            workers.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
